import os
import subprocess
import threading

import pandas as pd

from src.event.EventBus import Event, EventManager


class BaseMonitor:
    CMD = '''
    echo "swpd   free   buff  cache"; while true; do TIME=$(date "+%H:%M:%S.00"); echo $TIME 1 2 3 4 ; sleep 2; done
    '''
    CMD_PRE = []

    DUMMY = '''name1 name2 name3
10:00 1 2 3
10:01 2 2 2
10:02 3 4 5
10:03 1 2 3
10:04 1 8 5
10:05 2 8 7
10:06 1 2 1    
'''
    TAG = ''

    def __init__(self, name='th'):
        self.df_columns = []
        self.name = name
        self.TAG = '[' + name + ']'
        self.new_row = dict()
        self.data = pd.DataFrame()
        self.process = None
        self.thread = None
        self.is_alive = False

    def start(self, device_name=None):
        if self.is_alive is False:
            self.is_alive = True
            self.thread = threading.Thread(target=self.run, name=self.name, args=(self,))

            for cmd in self.CMD_PRE:
                cmd = cmd.replace("adb", "adb -s " + device_name)
                self.print('Pre cmd:' + cmd)
                os.system(cmd)

            self.CMD = self.CMD.replace("adb", "adb -s " + device_name)

            self.process = subprocess.Popen(self.CMD,
                                            bufsize=1,
                                            stdin=subprocess.PIPE,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            shell=True)
            self.thread.start()

    def stop(self):
        self.is_alive = False
        self.thread.join()
        EventManager.emit(Event(Event.ON_STATE_CHANGED, {'state': 'Stopped'}))
        self.process = None
        self.thread = None

    def state(self):
        return self.is_alive

    def run(self, arg):
        self.print('running...')
        self.print('Executing: ' + '\"' + self.CMD + '\"')
        EventManager.emit(Event(Event.ON_STATE_CHANGED, {'state': 'Running'}))

        # lines = BaseMonitor.DUMMY.split('\n')
        # for l in lines:
        #     if len(l) > 0:
        #         self.parse_line(l)
        #         EventManager.emit(Event(Event.ON_CHART_UPDATE))
        #         time.sleep(1)
        #
        #     if not self.is_alive:
        #         break

        # (stdout, stderr) = arg.process.communicate()
        while self.is_alive:
            line = self.process.stdout.readline().decode('utf-8')
            if len(line) > 0:
                self.parse_line(line)

    def parse_line(self, line):
        if len(self.df_columns) == 0:
            self.df_columns = line.split()
            self.data = pd.DataFrame(columns=self.df_columns, dtype=float)
            return

        print(line)
        elements = line.split()

        if len(elements) is not len(self.df_columns) + 1:
            return

        s = pd.Series(elements[1:], index=self.df_columns, name=elements[0], dtype=float)
        self.data = self.data.append(s)
        EventManager.emit(Event(Event.ON_CHART_UPDATE))

    def print(self, data):
        print(self.TAG + ' ' + data)
